<?php
	namespace core;
	use Illuminate\Database\Capsule\Manager as DbManager;
	use stdClass;
	//封装基本的查询方法
	abstract class  BaseService{
		abstract function model();
		
		function db(){
			return $this->db = App::DB();
		}
		
		function table($tName = null){
			if($tName==null) $tName = $this->model();
			return $this->db()->table($tName);
		}
		//插入数据
		function insert($attrArr,$returnId = false){
			if($returnId)
				return $this->table()->insertGetId($attrArr);
			else {
				return $this->table()->insert($attrArr);
			}
		}
		
		function getFirst($var=null,$val=null,$table=null){
			if($table==null) $table = $this->table();
			if($var!=null){
				return $table->where($var,'=',$val)->first();
			}else{
				return $table->first();
			}
		}
		
		function queryByFilter($paramFilter,$table=null){
			if($table==null) $table = $this->table();
			$paramFilter->where($table);
			$grid = new stdClass();
			$grid->total = $table->count();
			if(!empty($paramFilter->sort)){
				//支持多排序
				$sorts = explode(',',$paramFilter->sort);
				$orders = explode(',',$paramFilter->order);
				for($i=0;$i<count($sorts);$i++){
					$table->orderBy($sorts[$i],$orders[$i]);
				}
			}
			$skipCount = ($paramFilter->page-1)*$paramFilter->pageSize;
			$grid->rows = $table->skip($skipCount)->take($paramFilter->pageSize)->get();
			$paramFilter->grid = $grid;
		}
		
		//更新数据
		function update($attrs,$primaryKey = 'id'){
			$this->table()->where($primaryKey,$attrs[$primaryKey])->update($attrs);
		}
		
		//更新数据
		function updateByFilter($paramFilter,$attrs,$table=null){
			if($table==null) $table = $this->table();
			$paramFilter->where($table);
			$count = $table->update($attrs);
			$json=new stdClass();
			$json->success= true;
			$json->msg = "操作成功，已更新".$count."条数据！";
			return $json;
		}
		
		//删除数据
		function deleteByFilter($paramFilter,$table=null){
			if($table==null) $table = $this->table();
			$paramFilter->where($table);
			$count = $table->delete();
			$json=new stdClass();
			$json->success= true;
			$json->msg = "操作成功，已删除".$count."条数据！";
			return $json;
		}
	}